package com.ccteam.shared.domain.search

import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.map
import com.ccteam.shared.api.SearchDataSource
import com.ccteam.shared.data.search.HomeSearchAlbumPagingSource
import com.ccteam.shared.domain.PagingUseCase
import com.ccteam.shared.result.album.AlbumListItem
import com.ccteam.shared.utils.ALBUM_QUALITY
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/16
 *
 * 搜索专辑Domain层
 * 传入[String] 专辑名
 * 返回[AlbumListItem] 专辑列表
 */
class HomeSearchAlbumDataUseCase @Inject constructor(
    private val searchDataSource: SearchDataSource
): PagingUseCase<String?, AlbumListItem>(
    Dispatchers.IO
) {
    override fun execute(parameters: String?): Flow<PagingData<AlbumListItem>> {
        if(parameters.isNullOrEmpty()){
            return flowOf(PagingData.empty())
        }
        return Pager(
            PagingConfig(pageSize = 15,initialLoadSize = 15)
        ){
            HomeSearchAlbumPagingSource(parameters,searchDataSource)
        }.flow.map { pagingData ->
            pagingData.map {
                AlbumListItem(it.id,it.name,it.imgUrl + ALBUM_QUALITY,it.artistName,it.artistName,it.id,null,null)
            }
        }
    }

}